//
//  AppDelegate.m
//  DongFengDemo
//
//  Created by wxt on 2021/3/29.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "HomeViewController.h"
#import <CoreTelephony/CTCellularData.h>
#import "lognViewController.h"
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#import "ForgetPayWordViewController.h"
#import "SetUpFaceIDViewController.h"
#import "ChangeWordViewController.h"
#import "PayPassWordViewController.h"
#import "PassWordViewController.h"
#import "LoginPassWordViewController.h"
#import "RealReachability.h"
#import <AdSupport/ASIdentifierManager.h>
#import "FaceIDViewController.h"
#import "IQKeyboardManager.h"
#import "NewPayPasswordViewController.h"
#import "ChangeSuccessViewController.h"
#import "MoblieViewController.h"
#import "CodeViewController.h"
#import "LaunchViewController.h"
#endif
@interface AppDelegate ()<JPUSHRegisterDelegate,NoNetworkViewDelegate>
@property(nonatomic,strong)NSMutableArray * userNameArr;
@property(nonatomic,strong)NoNetworkView * noNetView;
@end

@implementation AppDelegate

-(NSMutableArray *)userNameArr{
    
    if (!_userNameArr) {
        _userNameArr = [NSMutableArray array];
    }
    return _userNameArr;
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.wiondow = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.wiondow.backgroundColor = Wcolor;
    [self.wiondow makeKeyAndVisible];

    [self listenNetWorkingStatus];
    [self jsPush:launchOptions];
    //信安初始化
  [self cerInitHost];
    [self setupIQKeyboardManager];
   
    [DataBaseTool openDataBaseAndCreateUserTable];
    [DataBaseTool openDataBaseAndCreateUserPINTable];

    [NSThread sleepForTimeInterval:2];
    
    
    
    
    return YES;
}

- (void)setupIQKeyboardManager
{
    // IQKeyboardManager
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
    keyboardManager.shouldShowToolbarPlaceholder = YES; // 是否显示占位文字
}

-(void)cerInitHost{
    
    NSString *serverCert1 = [[NSBundle mainBundle] pathForResource:@"root" ofType:@"cer"];

    NSArray * serverArr = @[serverCert1];
    NSString * hostUrl = @"59.172.234.206";
    NSString * portStr = @"20080";
    char appid[] = "JXIAnVGbkMW8w9DT";
    char appsecret[] = "SWOkgjd7VWrMBatxvLhBuKy2XzLw5vMS";
    int ret = infosec_initialize_with_key(hostUrl.UTF8String, [portStr intValue], serverArr, appid, strlen(appid), appsecret, strlen(appsecret));
   
    if (ret != 0) {
        [self selectDataList];
        NSLog(@"SDK 初始化失败");
        return;
    }
    NSLog(@"SDK 初始化成功");
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    
    
    
    IMUser  *user = [IMUser userWithUserName:[stand objectForKey:@"userName"]];
    
//    NSLog(@"%@",[stand objectForKey:@"userName"]);
    if (user == nil) {
        //查询数据库
     
        [self selectDataList];
        
    }else{
        
        [ user.cert getCertStateWithCompleteBlock:^(int resultCode, NSDictionary *dictState) {
                           NSLog(@"%d",resultCode);
            if (resultCode == IM_ER_SUCCESS) {
                NSLog(@"%@",dictState);
                if ([dictState[@"isexpired"] intValue] == 0) {
                    //查询数据库

                   [self selectDataList];
                }else{
                    
                    LaunchViewController * lanch = [[LaunchViewController alloc]init];
                    lanch.userName =[stand objectForKey:@"userName"];
                    lanch.pushPath = @"timeCer";
                    self.wiondow.rootViewController = lanch;

                }
            }else{
                [user.cert deleteCert];
                [self selectDataList];
            }
        }];
        
    }
    
  
    
    
    
    
    
}



-(void)jsPush:(NSDictionary *)launchOptions{

        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        if (@available(iOS 12.0, *)) {
                entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
            } else {
                // Fallback on earlier versions
            }

        
         if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
           // 可以添加自定义 categories
           // NSSet<UNNotificationCategory *> *categories for iOS10 or later
           // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
         }
         [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
        
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    [JPUSHService setupWithOption:launchOptions appKey:@"218fe57b11202fda89f0f572"
                           channel:@"App Store"
                  apsForProduction:@"0"
             advertisingIdentifier:advertisingId];
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        ////
        [JPUSHService setBadge:0];
    NSLog(@"advertisingId == %@",advertisingId);
    [JPUSHService setAlias:@"1000" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:(1)];

    
}
-(void)listenNetWorkingStatus{
    [GLobalRealReachability startNotifier];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkChanged:)
                                                 name:kRealReachabilityChangedNotification
                                               object:nil];
    ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
    [self realNetworkingStatus:status];
}
- (void)networkChanged:(NSNotification *)notification
{
    RealReachability *reachability = (RealReachability *)notification.object;
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    [self realNetworkingStatus:status];
}
-(void)realNetworkingStatus:(ReachabilityStatus)status{
    switch (status)
    {
            
        case RealStatusUnknown:
        {
            [MBProgressHUD showMessage:@"当前网络不可用" toView:self.wiondow];
        
            break;
        }
            
        case RealStatusNotReachable:
        {
        
//            NSLog(@"~~~~~~无网络~~~~~~~RealStatusNotReachable");
            [MBProgressHUD showMessage:@"无网络" toView:self.wiondow];
            break;
        }
            
        case RealStatusViaWWAN:
        {
//            NSLog(@"~~~~流量上网~~~~~~~~~RealStatusViaWWAN");
            [MBProgressHUD showMessage:@"您正在使用流量上网" toView:self.wiondow];
            
            break;
        }
        case RealStatusViaWiFi:
        {
//            NSLog(@"~~~~~WIFI~~~~~~~~RealStatusViaWiFi");
             [MBProgressHUD showMessage:@"已连接WIFI" toView:self.wiondow];

            break;
        }
        default:
            break;
    }
}
//- (void)testNetwork{
//
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSURLSession *session = [NSURLSession sharedSession];
//        NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
//        NSURLSessionTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        }];
//        [task resume];
//    });
//}
-(void)selectDataList{
    
    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from user "];
    FMResultSet *resultSet = [database executeQuery:selectSql];
    while ([resultSet next]) {
        NSLog(@"%@",resultSet);
    NSString *name = [resultSet stringForColumn:@"userName"];
        NSString *name1 = [resultSet stringForColumn:@"passWord"];
        NSLog(@"*****%@,%@",name,name1);
        [self.userNameArr addObject:name];
        
    }
    [database close];
    
    
    
    ViewController * viewVC = [[ViewController alloc]init];
    LognViewController * lognVC = [[LognViewController alloc]init];
    HomeViewController * homeVC = [[HomeViewController alloc]init];
    
    if (self.userNameArr.count > 0) {

        self.wiondow.rootViewController = lognVC;
    }else{
      
        self.wiondow.rootViewController = viewVC;
    }
}

#pragma mark - UISceneSession lifecycle

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

  /// Required - 注册 DeviceToken
  [JPUSHService registerDeviceToken:deviceToken];
}


- (void)networkDidReceiveMessage:(NSNotification *)notification {
        NSDictionary * userInfo = [notification userInfo];
    NSLog(@"%@",userInfo);
        NSString *content = [userInfo valueForKey:@"content"];
        NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
//        NSDictionary *extras = [userInfo valueForKey:@"extras"];
//        NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
    }
//APNs注册失败回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


//添加处理 APNs 通知回调方法
// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    

    
  if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //从通知界面直接进入应用
  }else{
    //从通知设置界面进入应用
  }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"%@",userInfo);
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionBadge); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"%@",userInfo);
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  // Required, iOS 7 Support
  [JPUSHService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [JPUSHService handleRemoteNotification:userInfo];
}


@end
